package ldh.im.fxbase.util;

import javafx.scene.Node;
import javafx.scene.web.HTMLEditor;
import javafx.scene.web.WebView;

import java.util.Set;

public class HtmlEditorUtil {

    public static HTMLEditor createHtmlEditor() {
        HTMLEditor htmlEditor = new HTMLEditor();
//        htmlEditor.prefHeightProperty().bind(htmlEditor);
        hideByClass(htmlEditor, ".top-toolbar", ".bottom-toolbar");
        return htmlEditor;
    }

    public static void noToolbar(HTMLEditor htmlEditor) {
        hideByClass(htmlEditor, ".top-toolbar", ".bottom-toolbar");
    }

    private static void hideByClass(HTMLEditor htmlEditor, String... selectors) {
        for (String selector : selectors) {
            Set<Node> nodes = htmlEditor.lookupAll(selector);
            for (Node node : nodes) {
                node.setVisible(false);
                node.setManaged(false);
            }
        }
    }

    public static String getWebViewHtml(WebView webView) {
        String msg =( String) webView.getEngine().executeScript("document.documentElement.outerHTML");
        return msg;
    }

    public static String getWebViewText(WebView webView) {
        String msg =( String) webView.getEngine().executeScript("document.documentElement.innerText");
        return msg;
    }

    public static void insertHtml(WebView webView, String html) {
        boolean isSuccess = false;
        try {
            webView.getEngine().executeScript("insertHtml(\"" + html + "\")");
            isSuccess = true;
        } catch (Exception e3) { }
        if (!isSuccess) {
            webView.getEngine().executeScript("placeCaretAtEnd(document.getElementById(\"endSpan\"))");
            webView.getEngine().executeScript("insertHtml(\"" + html + "\")");
        }
    }

}
